#pragma once

#include <string>
#include <memory>
#include <vector>
#include <functional>
#include <unordered_map>
#include <mutex>
#include <thread>
#include <atomic>
#include <chrono>

namespace hft {

// 前向声明
class TradingSystem;
struct MarketData;
struct MarketDataSnapshot;  // 添加MarketDataSnapshot前向声明
struct OrderBook;
struct Order;
struct Trade;
struct Position;
struct Account;

// 策略状态
enum class StrategyStatus {
    INITIALIZED,
    RUNNING,
    PAUSED,
    STOPPED
};

/**
 * @brief 策略接口类
 * 
 * 所有交易策略都需要继承此基类并实现相应接口
 */
class Strategy {
public:
    Strategy() = default;
    virtual ~Strategy() = default;

    /**
     * @brief 初始化策略
     * @param config 配置参数
     * @return 是否初始化成功
     */
    virtual bool init(const std::string& config) = 0;

    /**
     * @brief 启动策略
     * @return 是否启动成功
     */
    virtual bool start() = 0;

    /**
     * @brief 停止策略
     */
    virtual void stop() = 0;

    /**
     * @brief 处理行情数据
     * @param data 行情数据
     */
    virtual void onMarketData(const MarketData& data) = 0;

    /**
     * @brief 处理订单簿更新
     * @param orderBook 订单簿数据
     */
    virtual void onOrderBookUpdate(const OrderBook& orderBook) = 0;

    /**
     * @brief 处理订单状态更新
     * @param order 订单信息
     */
    virtual void onOrderUpdate(const Order& order) = 0;

    /**
     * @brief 处理订单成交
     * @param trade 成交信息
     */
    virtual void onOrderFilled(const Trade& trade) = 0;

    /**
     * @brief 处理订单取消
     * @param order 订单信息
     */
    virtual void onOrderCancelled(const Order& order) = 0;

    // 获取策略信息
    virtual std::string getName() const = 0;
    virtual std::string getStatus() const = 0;
    virtual int getStrategyId() const = 0;
    
    // 设置交易系统引用
    void setTradingSystem(TradingSystem* system) { trading_system_ = system; }
    
protected:
    TradingSystem* trading_system_{nullptr};  // 交易系统引用
    
    // 设置订单执行回调
    void setOrderCallback(std::function<void(const Order&)> callback) {
        order_callback_ = callback;
    }

protected:
    std::string name_;
    StrategyStatus status_;
    std::function<void(const Order&)> order_callback_;

    // 策略参数
    struct StrategyParams {
        std::string name;                         // 策略名称
        double spread_multiplier;                 // 价差倍数
        double min_spread;                        // 最小价差
        int64_t max_position;                     // 最大持仓
        int64_t order_refresh_interval;           // 订单刷新间隔(ms)
        int64_t max_orders;                       // 最大挂单数
        int64_t min_volume;                       // 最小下单量
        int64_t max_volume;                       // 最大下单量
        double price_tick;                        // 价格最小变动
        int64_t volume_multiple;                  // 合约乘数
    } params_;

    // 策略状态
    struct StrategyState {
        std::unordered_map<std::string, MarketDataSnapshot> market_data;  // 最新行情
        std::unordered_map<std::string, Position> positions;              // 当前持仓
        std::unordered_map<std::string, Order> active_orders;            // 活动订单
        Account account;                                                  // 账户信息
    } state_;

    // 策略线程
    std::thread strategy_thread_;
    std::atomic<bool> running_{false};

    // 互斥锁
    std::mutex mutex_;

    // 策略主循环
    void run();

    // 计算买卖价格
    void calculatePrices(const std::string& symbol, double& bid_price, double& ask_price);

    // 检查是否需要调整订单
    bool needAdjustOrders(const std::string& symbol);

    // 调整订单
    void adjustOrders(const std::string& symbol);

    // 发送订单（纯虚函数，由子类实现）
    virtual std::string sendOrder(const Order& order) = 0;

    // 发送订单（便捷方法）
    bool sendOrderWithDetails(const std::string& symbol, OrderDirection direction, OrderOffset offset,
                  double price, int64_t volume);

    // 撤销订单
    bool cancelOrder(const std::string& order_id);
};

// 策略工厂
// 前置声明策略类
class MarketMakerStrategy;
class TrendFollowingStrategy; 
class StatisticalArbitrageStrategy;
class HighFrequencyStrategy;

class StrategyFactory {
public:
    static std::shared_ptr<Strategy> createStrategy(const std::string& name) {
        if (name == "market_maker") {
            return std::make_shared<MarketMakerStrategy>();
        } else if (name == "trend_following") {
            return std::make_shared<TrendFollowingStrategy>();
        } else if (name == "statistical_arbitrage") {
            return std::make_shared<StatisticalArbitrageStrategy>();
        } else if (name == "high_frequency") {
            return std::make_shared<HighFrequencyStrategy>();
        }
        return nullptr;
    }
};

// 交易信号结构
struct Signal {
    enum class Type {
        BUY,    // 买入信号
        SELL,   // 卖出信号
        HOLD    // 持仓信号
    };
    
    Type type;          // 信号类型
    double price;       // 价格
    int64_t quantity;   // 数量
    std::string symbol; // 交易品种
    std::chrono::system_clock::time_point timestamp;  // 时间�?
};

// 均值回归策略
class MeanReversionStrategy : public Strategy {
public:
    MeanReversionStrategy() = default;
    ~MeanReversionStrategy() override = default;
    
    bool init(const std::string& config) override;
    bool start() override;
    void stop() override;
    void onMarketData(const MarketData& data) override;
    void onOrderBookUpdate(const OrderBook& orderBook) override;
    void onOrderUpdate(const Order& order) override;
    void onOrderFilled(const Trade& trade) override;
    void onOrderCancelled(const Order& order) override;
    
    std::string getName() const override { return "MeanReversionStrategy"; }
    std::string getStatus() const override { 
        return running_ ? "RUNNING" : "STOPPED"; 
    }
    int getStrategyId() const override { return 5; }
    
    std::string sendOrder(const Order& order) override {
        // 实现订单发送逻辑
        return "order_id";
    }

private:
    std::string symbol_;           // 交易品种
    double lookback_period_;       // 回溯期
    double entry_threshold_;       // 入场阈值
    double exit_threshold_;        // 出场阈值
    std::vector<double> price_history_;  // 价格历史
    bool running_{false};
    
    double calculateMean() const;      // 计算均值
    double calculateStdDev() const;    // 计算标准差
    Signal generateSignal(const OrderBook& book);  // 生成交易信号
};

// 趋势跟踪策略
class TrendFollowingStrategy : public Strategy {
public:
    TrendFollowingStrategy() = default;
    ~TrendFollowingStrategy() override = default;
    
    bool init(const std::string& config) override;
    bool start() override;
    void stop() override;
    void onMarketData(const MarketData& data) override;
    void onOrderBookUpdate(const OrderBook& orderBook) override;
    void onOrderUpdate(const Order& order) override;
    void onOrderFilled(const Trade& trade) override;
    void onOrderCancelled(const Order& order) override;
    
    std::string getName() const override { return "TrendFollowingStrategy"; }
    std::string getStatus() const override { 
        return running_ ? "RUNNING" : "STOPPED"; 
    }
    int getStrategyId() const override { return 2; }
    
    std::string sendOrder(const Order& order) override {
        // 实现订单发送逻辑
        return "order_id";
    }

private:
    std::string symbol_;           // 交易品种
    int short_window_;            // 短期窗口
    int long_window_;             // 长期窗口
    std::vector<double> price_history_;  // 价格历史
    bool running_{false};
    
    double calculateShortMA() const;    // 计算短期移动平均
    double calculateLongMA() const;     // 计算长期移动平均
    Signal generateSignal(const OrderBook& book);  // 生成交易信号
};

// 做市商策略
class MarketMakerStrategy : public Strategy {
public:
    bool init(const std::string& config) override;
    bool start() override;
    void stop() override;
    void onMarketData(const MarketData& data) override;
    void onOrderBookUpdate(const OrderBook& orderBook) override;
    void onOrderUpdate(const Order& order) override;
    void onOrderFilled(const Trade& trade) override;
    void onOrderCancelled(const Order& order) override;
    
    std::string getName() const override { return "MarketMakerStrategy"; }
    std::string getStatus() const override { 
        return running_ ? "RUNNING" : "STOPPED"; 
    }
    int getStrategyId() const override { return 1; }
    
    std::string sendOrder(const Order& order) override {
        // 实现订单发送逻辑
        return "order_id";
    }

private:
    void calculatePrices();
    void manageOrders();
    void checkRisk();

    double spread_multiplier_;
    double min_spread_;
    int64_t max_position_;
    int64_t order_refresh_interval_;
    int64_t max_orders_;
    int64_t min_volume_;
    int64_t max_volume_;
    double price_tick_;
    int64_t volume_multiple_;

    std::unordered_map<std::string, MarketData> market_data_;
    std::unordered_map<std::string, Position> positions_;
    std::unordered_map<std::string, std::vector<Order>> active_orders_;
    Account account_;
    bool running_{false};
};

// 统计套利策略
class StatisticalArbitrageStrategy : public Strategy {
public:
    StatisticalArbitrageStrategy() = default;
    ~StatisticalArbitrageStrategy() override = default;
    
    bool init(const std::string& config) override;
    bool start() override;
    void stop() override;
    void onMarketData(const MarketData& data) override;
    void onOrderBookUpdate(const OrderBook& orderBook) override;
    void onOrderUpdate(const Order& order) override;
    void onOrderFilled(const Trade& trade) override;
    void onOrderCancelled(const Order& order) override;
    
    std::string getName() const override { return "StatisticalArbitrageStrategy"; }
    std::string getStatus() const override { 
        return running_ ? "RUNNING" : "STOPPED"; 
    }
    int getStrategyId() const override { return 3; }
    
    std::string sendOrder(const Order& order) override {
        // 实现订单发送逻辑
        return "order_id";
    }

private:
    void calculateSpread();
    void detectMeanReversion();
    void executePairs();

    int64_t lookback_period_;
    double entry_threshold_;
    double exit_threshold_;
    double stop_loss_;
    int64_t max_position_;
    std::vector<std::pair<std::string, std::string>> pairs_;

    std::unordered_map<std::string, std::vector<double>> prices_;
    std::unordered_map<std::string, std::vector<double>> spreads_;
    std::unordered_map<std::string, Position> positions_;
    std::unordered_map<std::string, std::vector<Order>> active_orders_;
    Account account_;
    bool running_{false};
};

// 高频交易策略
class HighFrequencyStrategy : public Strategy {
public:
    HighFrequencyStrategy() = default;
    ~HighFrequencyStrategy() override = default;
    
    bool init(const std::string& config) override;
    bool start() override;
    void stop() override;
    void onMarketData(const MarketData& data) override;
    void onOrderBookUpdate(const OrderBook& orderBook) override;
    void onOrderUpdate(const Order& order) override;
    void onOrderFilled(const Trade& trade) override;
    void onOrderCancelled(const Order& order) override;
    
    std::string getName() const override { return "HighFrequencyStrategy"; }
    std::string getStatus() const override { 
        return running_ ? "RUNNING" : "STOPPED"; 
    }
    int getStrategyId() const override { return 4; }
    
    std::string sendOrder(const Order& order) override {
        // 实现订单发送逻辑
        return "order_id";
    }

private:
    void detectOpportunities();
    void executeTrades();
    void manageRisk();

    int64_t min_tick_size_;
    int64_t max_position_;
    double min_profit_;
    int64_t max_holding_time_;
    double stop_loss_;
    double take_profit_;

    std::unordered_map<std::string, MarketData> market_data_;
    std::unordered_map<std::string, Position> positions_;
    std::unordered_map<std::string, std::vector<Order>> active_orders_;
    Account account_;
    bool running_{false};
};

} // namespace hft 